/******************************************************************************

  Copyright (C), 2014-, GuangZhou JUAN Electronics Co., Ltd.

 ******************************************************************************
  File Name    : ja_process.h
  Version       : Initial Draft
  Author        : wengson@sina.com(wenson)
  Created       : 2015/9/25
  Last Modified : 2015/9/25
  Description   : juan process API

  History       :
  1.Date        : 2015/9/25
    	Author      : wenson
 	Modification: Created file
******************************************************************************/

#ifndef __NK_PROCESS_H__
#define __NK_PROCESS_H__


#ifdef __cplusplus
extern "C" {
#endif

#include "string.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static inline int IS_VALID_IPADDR(char *ipaddr)
{
	int ip[4];
	if(NULL == ipaddr || 4 != sscanf(ipaddr, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3])
		|| 4 > ip[0]
		|| 127 == ip[0]
		|| 224 <= ip[0]
		|| 0 > ip[1]
		|| 255 < ip[1]
		|| 0 > ip[2]
		|| 255 < ip[2]
		|| 168 == ip[2]
		|| 0 >= ip[3]
		|| 255 <= ip[3]){
		printf("invalid IP:%s\r\n", ipaddr);
		return 0;
	}
	return 1;
}

static inline int IS_VALID_NETMASK(char *ipaddr)
{
    unsigned int b = 0, i, n[4];  
    if(NULL != ipaddr && 4 == sscanf(ipaddr, "%u.%u.%u.%u", &n[3], &n[2], &n[1], &n[0])){
        for(i = 0; i < 4; ++i) //将子网掩码存入32位无符号整型   
            b += n[i] << (i * 8);   
        b = ~b + 1;  
        if((b & (b - 1)) == 0){   //判断是否为2^n   
            return 1; 
        }
    }
	printf("invalid netmask:%s\r\n", ipaddr);
    return 0;
}

static inline int IS_VALID_GATEWAY(char *ipaddr, char *netmask, char *gateway)
{
	unsigned int ip, mask,gw;
	if(IS_VALID_IPADDR(ipaddr) && IS_VALID_NETMASK(netmask) && IS_VALID_IPADDR(gateway)){
		ip = inet_addr(ipaddr);
		mask = inet_addr(netmask);
		gw = inet_addr(gateway);
		if((ip & mask) == (gw & mask)){
			return 1;
		}	
	}
	printf("invalid gateway:%s\r\n", gateway);	
	return 0;
}

#ifdef WIN32
typedef unsigned long	NK_PID_t;
#else
typedef pid_t	NK_PID_t;
#endif

#define NK_SYSTEM(cmdline)\
	do{\
		const char* bname = basename(strdupa(__FILE__));\
		int const syntax_fg = ((bname[0] >> 8) + (bname[0] & 0xff)) % 8;\
		printf("\033[1;%dm[%12s:%4d]\033[0m ", 30 + syntax_fg, bname, __LINE__);\
		printf("system cmd: %s", cmdline);\
		printf("\r\n");\
		system(cmdline);\
	}while(0)


#ifdef __cplusplus
}
#endif

#endif